package net.risesoft.risebi.collection.web.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.risesoft.risebi.collection.model.Application;
import net.risesoft.risebi.collection.model.ReportInstance;
import net.risesoft.risebi.collection.model.ReportWindowPeriod;
import net.risesoft.risebi.collection.model.Template;
import net.risesoft.risebi.collection.service.ApplicationManager;
import net.risesoft.risebi.collection.service.ReportInstanceManager;
import net.risesoft.risebi.collection.service.ReportPeriodManager;
import net.risesoft.risebi.collection.service.ReportWindowPeriodManager;
import net.risesoft.risebi.collection.service.TemplateManager;
import net.risesoft.risebi.collection.web.BaseAction;
import net.risesoft.risebi.commons.util.GUID;
import net.risesoft.risebi.commons.util.JSONUtil;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;

/**
*
* @author <a href="mailto: baiyibing@gmail.com">王锤</a>
* @version $Revision$
* 
*/
@Namespace("/admin/ReportWindowPeriodAction")
public class ReportWindowPeriodAction extends BaseAction {
	private static final long serialVersionUID = -5045799522135010888L;
	private static final Logger logger = Logger.getLogger(ReportWindowPeriodAction.class);

	private ReportWindowPeriod reportWindowPeriod;
	private String reportWindowPeriodGuid;
	private String jsonObjects;
	private String applicationGuid;
	private String templateGuid;
	private Template template;
	private boolean toBeInit;
	
	private ReportWindowPeriodManager reportWindowPeriodManager;
	private ReportInstanceManager reportInstanceManager;
	private ApplicationManager applicationManager;
	private ReportPeriodManager reportPeriodManager;
	private TemplateManager templateManager;
	
	@Action(value="listTemplate",
			results={@Result(name="success", location="/admin/reportwindowperiod/listTemplate.jsp")}
	)
	public String listTemplate() throws Exception {		
		return SUCCESS;
	}
	
	@Action(value="prepareManager",
			results={@Result(name="success", location="/admin/reportwindowperiod/windowPeriodManager.jsp")}
	)
	public String prepareManager() throws Exception {		
		this.template = (Template)templateManager.getObject(Template.class, this.templateGuid);
		
		return SUCCESS;  
	}   

	@Action(value="prepareEdit",
			results={@Result(name="success", location="/admin/reportwindowperiod/windowPeriodEdit.jsp")}
	)
	public String prepareEdit() throws Exception {		
		this.reportWindowPeriod = (ReportWindowPeriod)reportWindowPeriodManager.getObject(ReportWindowPeriod.class, this.reportWindowPeriodGuid);
		
		return SUCCESS;  
	}
	
	@Action(value="updateBatch")
	public String updateBatch() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			if(this.jsonObjects.trim().length()>0){
				ReportWindowPeriod[] ps = (ReportWindowPeriod[])JSONUtil.stringToArray(this.jsonObjects, ReportWindowPeriod.class);
				for (ReportWindowPeriod p : ps){
					reportWindowPeriodManager.saveObject(p);
				}
			}
			
			ldb.set("success", true);
			ldb.set("reason", "保存成功!");
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
			e.printStackTrace();
		}

		return AJAX;
	}
	
	@Action(value="edit")
	public String edit() throws Exception {
		LazyDynaBean ldb = new  LazyDynaBean();
		try{
			ReportWindowPeriod old = (ReportWindowPeriod)reportWindowPeriodManager.getObject(ReportWindowPeriod.class, this.reportWindowPeriod.getGuid());
			old.setIsOpen(reportWindowPeriod.getIsOpen());
			old.setLateDate(reportWindowPeriod.getLateDate());
			old.setLockDate(reportWindowPeriod.getLockDate());
			old.setUnlockDate(reportWindowPeriod.getUnlockDate());
			old.setUrgeDate(reportWindowPeriod.getUrgeDate());
			
			reportWindowPeriodManager.saveObject(old);	
			
			ldb.set("guid", old.getGuid());
			ldb.set("templateGuid", old.getTemplateGuid());
			ldb.set("reportPeriodGuid", old.getReportPeriodGuid());
			ldb.set("reportPeriodName", old.getReportPeriodName());
			ldb.set("unlockDate", old.getUnlockDate());
			ldb.set("lockDate", old.getLockDate());
			ldb.set("lateDate", old.getLateDate());			
			ldb.set("urgeDate", old.getUrgeDate());	
			ldb.set("isOpen", old.getIsOpen());
			
			ldb.set("success", true);
			ldb.set("reason", "修改成功!");
			
			this.json = JSONObject.fromObject(ldb).toString();
		}catch(Exception e){
			ldb.set("success", false);
			ldb.set("reason", e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}

		return AJAX;
	}
	
	@Action(value="removeAll")
	public String removeAll() throws Exception {
		LazyDynaBean ldb = new LazyDynaBean();
		try {

			if ("all".equalsIgnoreCase(this.jsonObjects)) { // 全部删除。
				Integer count = reportInstanceManager.getCount("select count(*) from ReportInstance r where r.reportWindowPeriod in ( from ReportWindowPeriod t where t.template.guid='" + this.templateGuid + "')");
				if (count > 0) {
					ldb.set("success", false);
					ldb.set("reason", "填报名录中包含了某些窗口期，不允许删除全部，只能删除不在填报名录中的窗口期！");
				}else{
					reportWindowPeriodManager.execute("delete from ReportWindowPeriod r where r.template.guid='" + this.templateGuid + "'");		
					ldb.set("success", true);
					ldb.set("reason", "全部删除成功!");
				}
			} else {
				if (this.jsonObjects.trim().length() > 0) {
					String[] reportWindowPeriodGuids = this.jsonObjects.split(",");
					for (String reportWindowPeriodGuid : reportWindowPeriodGuids) {
						Integer count = reportInstanceManager.getCount("select count(*) from ReportInstance r where r.reportWindowPeriod.guid='" + reportWindowPeriodGuid + "'");
						if (count > 0) {
							ldb.set("success", false);
							ldb.set("reason", "该窗口期已经进入了填报名录，不允许删除，只能删除不在填报名录中的窗口期！");
							this.json = JSONObject.fromObject(ldb).toString();
							return AJAX;
						}
						reportWindowPeriodManager.removeObject(ReportWindowPeriod.class, reportWindowPeriodGuid);
					}
				}
				ldb.set("success", true);
				ldb.set("reason", "删除成功!");
			}

			this.json = JSONObject.fromObject(ldb).toString();
		} catch (Exception e) {
			ldb.set("success", false);
			ldb.set("reason", "删除失败:" + e.getMessage());
			this.json = JSONObject.fromObject(ldb).toString();
		}
		return AJAX;
	}
	
	public String Init() throws Exception {
		return "init";
	}

	@Action(value="refreshJson")
	public String refreshJson() throws Exception {
		this.applicationGuid = this.getDefaultApp().getGuid();
		try{
			if("jsonWindowPeriods".equalsIgnoreCase(this.whichJson)){
				if(this.toBeInit){
					reportWindowPeriodManager.initReportWindowPeriod(templateGuid);
				}
				Map map = reportWindowPeriodManager.getPagedByAppTemplateGuid(this.applicationGuid, templateGuid, start, limit);
				
				this.json = JSONUtil.getJsonString("include", "count,list,guid,templateGuid,reportPeriodGuid,unlockDate,lockDate,lateDate,urgeDate,templateCode,reportPeriodName,isOpen", map);		
			}else if("jsonApplications".equalsIgnoreCase(this.whichJson)){
				ArrayList al = new ArrayList();	
				Map map = new HashMap();
				if(this.active_node_id==null){
					Application application = (Application) applicationManager.getObject(Application.class, this.applicationGuid);
					List<Template> lst = application.getTemplates();
					int i = 0;
					for(Template a : lst){
						if(a.getBaseInfo()==true) continue; //基本表不设置窗口期。
						
						i++;
						boolean isleaf = true;
						Integer count = reportWindowPeriodManager.getCount("select count(*) from ReportWindowPeriod t where t.template.guid='" + a.getGuid() + "' and t.template.application.guid='" + this.applicationGuid + "'");
						if(count>0){
							isleaf = false;
						}
						LazyDynaBean ldb = new LazyDynaBean();
						ldb.set("guid", a.getGuid());
						ldb.set("parentGuid", "");
						
						if(a.getReportPeriodType()==null){
							ldb.set("name", a.getName() + "(总" + String.valueOf(count) + "条)");
						}else{
							ldb.set("name", a.getName() + "(" + a.getReportPeriodType().getName() + ",总" + String.valueOf(count) + "条)");
						}
						
						ldb.set("_node_type", "3");  //template
						ldb.set("_is_leaf", isleaf);
						al.add(ldb);
					}
					map.put("count", i);
					map.put("list", al);
				}else if("3".equalsIgnoreCase(this.active_node_type)){  //template
					Map map2 = reportWindowPeriodManager.getPagedByAppTemplateGuid(this.applicationGuid, this.active_node_id, start, limit);
					List<ReportWindowPeriod> lst = (List<ReportWindowPeriod>)map2.get("list");
					for(ReportWindowPeriod a : lst){
						LazyDynaBean ldb = new LazyDynaBean();
						ldb.set("guid", a.getGuid());
						ldb.set("parentGuid",a.getTemplateGuid());
						ldb.set("name", a.getReportPeriod().getName());
						ldb.set("_node_type", "5");
						ldb.set("_is_leaf", true);
						al.add(ldb);
					}
					map.put("count", map2.get("count"));
					map.put("list", al);
				}
				this.json = JSONUtil.getJsonString(null, null, map);				
			}
		}catch(Exception e){
			this.json = "[]";
			e.printStackTrace();
		} 

		return AJAX;
	}

	public String getJsonObjects() {
		return jsonObjects;
	}

	public void setJsonObjects(String jsonObjects) {
		this.jsonObjects = jsonObjects;
	}

	public String getApplicationGuid() {
		return applicationGuid;
	}

	public void setApplicationGuid(String applicationGuid) {
		this.applicationGuid = applicationGuid;
	}

	public String getTemplateGuid() {
		return templateGuid;
	}

	public void setTemplateGuid(String templateGuid) {
		this.templateGuid = templateGuid;
	}

	public boolean isToBeInit() {
		return toBeInit;
	}

	public void setToBeInit(boolean toBeInit) {
		this.toBeInit = toBeInit;
	}

	public ReportWindowPeriodManager getReportWindowPeriodManager() {
		return reportWindowPeriodManager;
	}

	public void setReportWindowPeriodManager(
			ReportWindowPeriodManager reportWindowPeriodManager) {
		this.reportWindowPeriodManager = reportWindowPeriodManager;
	}

	public ApplicationManager getApplicationManager() {
		return applicationManager;
	}

	public void setApplicationManager(ApplicationManager applicationManager) {
		this.applicationManager = applicationManager;
	}

	public ReportPeriodManager getReportPeriodManager() {
		return reportPeriodManager;
	}

	public void setReportPeriodManager(ReportPeriodManager reportPeriodManager) {
		this.reportPeriodManager = reportPeriodManager;
	}

	public TemplateManager getTemplateManager() {
		return templateManager;
	}

	public void setTemplateManager(TemplateManager templateManager) {
		this.templateManager = templateManager;
	}

	public static long getSerialVersionUID() {
		return serialVersionUID;
	}

	public static Logger getLogger() {
		return logger;
	}

	public Template getTemplate() {
		return template;
	}

	public void setTemplate(Template template) {
		this.template = template;
	}

	public ReportInstanceManager getReportInstanceManager() {
		return reportInstanceManager;
	}

	public void setReportInstanceManager(ReportInstanceManager reportInstanceManager) {
		this.reportInstanceManager = reportInstanceManager;
	}

	public ReportWindowPeriod getReportWindowPeriod() {
		return reportWindowPeriod;
	}

	public void setReportWindowPeriod(ReportWindowPeriod reportWindowPeriod) {
		this.reportWindowPeriod = reportWindowPeriod;
	}

	public String getReportWindowPeriodGuid() {
		return reportWindowPeriodGuid;
	}

	public void setReportWindowPeriodGuid(String reportWindowPeriodGuid) {
		this.reportWindowPeriodGuid = reportWindowPeriodGuid;
	}

}
